package com.csu.tingtian.service.impl;

import com.csu.tingtian.common.CommonResponse;
import com.csu.tingtian.persistence.MessageMapper;
import com.csu.tingtian.service.MessageService;
import com.csu.tingtian.vo.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service("MessageService")
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Override
    public CommonResponse<Message> userSendMessageToFarm(String userName, String farmName, String userContent) {
        Message message = new Message();
        message.setUserName(userName);
        message.setFarmName(farmName);
        message.setUserContent(userContent);
        message.setUserContentTime(getSystemTime());
        int i = messageMapper.insert(message);

        if (i > -1){
            return CommonResponse.createForSuccess(message);
        }
        else
            return CommonResponse.createForError("服务器异常,用户发送信息失败");
    }
    private String getSystemTime() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time= sdf.format( new Date());
        return time;
    }

    @Override
    public CommonResponse<Message> farmSendMessageTouser(String farmName, String userName, String farmContent) {
        Message message = new Message();
        message.setFarmName(farmName);
        message.setUserName(userName);
        message.setFarmContent(farmContent);
        message.setUserContentTime(getSystemTime());

        int i = messageMapper.insert(message);
        if (i > -1){
            return CommonResponse.createForSuccess(message);
        }
        else
            return CommonResponse.createForError("服务器异常,向用户发送信息失败");
    }

    @Override
    public CommonResponse<List<Message>> getMessage(String userName,String farmName) {
        List<Message> messageList = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        map.put("userName", userName);
        map.put("farmName",farmName);
        messageList = messageMapper.selectByMap(map);

        if (messageList != null){
            return CommonResponse.createForSuccess(messageList);
        }
        else
            return CommonResponse.createForError("服务器异常,未查询到聊天记录");
    }

    @Override
    public CommonResponse<Message> deleteMessage(String userName,String farmName) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userName", userName);
        map.put("farmName",farmName);
        int i  = messageMapper.deleteByMap(map);

        if (i > -1){
            return CommonResponse.createForSuccessMessage("用户" + userName + "和商家" + farmName + "的聊天记录已删除");
        }
        else
            return CommonResponse.createForError("服务器异常,未查询到聊天记录");
    }
}
